package rs.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;

public class Config {
	

	public static String NS_GLOBAL = "global";
	

	public static String FOLDER_PATH = "config/";
	
	public static HashMap<String, Properties> propMap = new HashMap<String, Properties>();
	
	public static Properties getProperties(String namespace){
		Properties prop = propMap.get(namespace);
		if(prop == null){
			prop = new Properties();
			FileInputStream fis = null;
			try {
				fis = new FileInputStream(FOLDER_PATH + namespace + ".xml");
				prop.loadFromXML(fis);
				propMap.put(namespace, prop);
			} catch (InvalidPropertiesFormatException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				if(fis != null){
					try {
						fis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return prop;
	}
	
	public static String getString(String namespace,String configName){
		return getProperties(namespace).getProperty(configName);
	}
	
	public static String getString(String namespace,String configName, String defaultValue){
		try{
			return getProperties(namespace).getProperty(configName, defaultValue);
		} catch (Exception e) {
			//log.error("Config: No config find for " + configName + " @ " + FOLDER_PATH + "config.xml");
			return defaultValue;
		}
	}
	
	public static int getInt(String namespace,String configName){
		return Integer.parseInt(getString(namespace,configName));
	}
	
	public static int getInt(String namespace,String configName, int defaultValue){
		return Integer.parseInt(getString(namespace,configName, String.valueOf(defaultValue)));
	}
	
	public static long getLong(String namespace,String configName){
		return Long.parseLong(getString(namespace,configName));
	}
	
	public static long getLong(String namespace,String configName, long defaultValue){
		return Long.parseLong(getString(namespace,configName, String.valueOf(defaultValue)));
	}
	
	public static double getDouble(String namespace,String configName, double defaultValue){
		return Double.parseDouble(getString(namespace,configName, String.valueOf(defaultValue)));
	}
	
	public static float getFloat(String namespace,String configName, float defaultValue){
		return Float.parseFloat(getString(namespace,configName,String.valueOf(defaultValue)));
	}
	
	
	public static void main(String[] args) {
		System.out.println(getLong(NS_GLOBAL,"schedule.relauchTime"));
		System.out.println(getString(NS_GLOBAL, "proxy.checkUrl"));
	}
}
